var gulp = require('gulp');
var change = require('gulp-changed');
var connect = require('gulp-connect');
var postcss = require('gulp-postcss');
var px2rem = require('postcss-px2rem');
var sass = require('gulp-ruby-sass');
var cssmin = require('gulp-minify-css');
var cssver = require('gulp-make-css-url-version');
var htmlmin = require('gulp-htmlmin');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin'); //压缩图片
//修改文件
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var map = require('event-stream').map;

var src = {
    css:['./src/css/*.css','!./src/css/vote_m.css'],
    css_m:'./src/css/vote_m.css',
    js:'./src/js/*.js',
    sass:'./src/css/*.scss',
    img : './src/img/',
    root:'./src/*.html',
    build:'./dist/',
    ug:'./uglified/'
};

gulp.task('server',function () {
    connect.server({
        root:'dist',
        port:8888,
        livereload:true
    })
});

gulp.task('watch',function () {
    gulp.watch(src.root,['html']);
    gulp.watch(src.js,['js']);
    gulp.watch(src.css,['css']);
    gulp.watch(src.css_m,['cssMobile']);
    gulp.watch(src.sass,['sass']);
    gulp.watch(src.img+"*",['imagemin']);
    gulp.watch('./src/responsive/*',['response']);
});
gulp.task('sass',function () {
    sass(src.sass,{style:'expanded'})
        .pipe(gulp.dest(src.build+'css'))
        .pipe(connect.reload());
});
gulp.task('html',function () {
    gulp.src(src.root)
        .pipe(gulp.dest(src.build))
        .pipe(connect.reload());
});

gulp.task('js',function () {
    gulp.src(src.js)
        .pipe(gulp.dest(src.build+'js'))
        .pipe(connect.reload());
});

gulp.task('css',function () {
    gulp.src(src.css)
        .pipe(gulp.dest(src.build+'css'))
        .pipe(connect.reload());
});
gulp.task('cssMobile',function () {
    var processors = [px2rem({remUnit: 75})];
    gulp.src(src.css_m)
        .pipe(postcss(processors))
        .pipe(gulp.dest(src.build+'css'))
        .pipe(connect.reload());
});
gulp.task('imagemin', function() {
    gulp.src(src.img+'*.{jpg,png,gif}')
        .pipe(imagemin())
　　　　　　　　//压缩后放在那个文件夹
        .pipe(gulp.dest(src.build+"img"))
        .pipe(connect.reload());
});
gulp.task('response',function(){
    gulp.src('./src/responsive/*')
    .pipe(gulp.dest(src.build+'responsive'))
    .pipe(connect.reload());
});

gulp.task('ugCssmin', function () {
    gulp.src(src.build+'/css/{reset,font,vote,vote_m}.css')
        .pipe(cssver()) //给css文件里引用文件加版本号（文件MD5）
        .pipe(cssmin({
            advanced: true,//类型：Boolean 默认：true [是否开启高级优化（合并选择器等）]
            compatibility: 'ie7',//保留ie7及以下兼容写法 类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
            keepBreaks: false,//类型：Boolean 默认：false [是否保留换行]
            keepSpecialComments: '*'
            //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀，如果不加这个参数，有可能将会删除你的部分前缀
        }))
        .pipe(gulp.dest(src.ug+'css'))
});

gulp.task('ugHtmlmin', function () {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    gulp.src(src.build+'/*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest(src.ug))
});
gulp.task('ugHtmlminTest', function () {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    gulp.src(src.build+'/*.html')
        .pipe(htmlmin(options))
        .pipe(changeLink())
        .pipe(gulp.dest(src.ug))
});

gulp.task('combine', function() {
    gulp.src(src.build+'/css/{reset,font,vote,vote_m}.css')
        .pipe(concat('page.css'))
        .pipe(cssver()) //给css文件里引用文件加版本号（文件MD5）
        .pipe(cssmin({
            advanced: true,//类型：Boolean 默认：true [是否开启高级优化（合并选择器等）]
            compatibility: 'ie7',//保留ie7及以下兼容写法 类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
            keepBreaks: false,//类型：Boolean 默认：false [是否保留换行]
            keepSpecialComments: '*'
            //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀，如果不加这个参数，有可能将会删除你的部分前缀
        }))
        .pipe(gulp.dest(src.ug+'css'))
});

gulp.task('jsmin', function () {
    gulp.src(src.build+'js/vote.js')
        .pipe(uglify())
        .pipe(gulp.dest(src.build+'js'))
});

//gulp.task('default',['server','watch','html','js','css','sass','combine']);
gulp.task('default',['server','watch','html','js','css','sass','imagemin','cssMobile','response']);

function changeLink() {;
    return map(function(file, cb) {
        //试试看修改文件的缓存
        var FILE_DECL = new RegExp("(<link(\[^<>\]*?)(href\\s*=\\s*\[\"\'\]\\s*css\\/(reset|font|vote|vote_m)\\.css)([^<>]*?)>){4}","gi");
        console.log(FILE_DECL);
        var contents;
        var lines;
        var i, length;
        var line;
        var declarations;
        var data, hash;
        contents = file.contents.toString();
        lines = contents.split('\n');
        length = lines.length;
        for(i = 0; i < length; i++) {
            line = lines[i];
            declarations = line.match(FILE_DECL);
            if (declarations && declarations.length > 0) {
                for(var j = 0; j < declarations.length; j++) {
                    try {
                        data = fs.readFileSync(file.path);
                        hash = crypto.createHash('md5');
                        hash.update(data.toString(), 'utf8');
                        line = line.replace(FILE_DECL, function () {
                            return "<link rel=\"stylesheet\" href=\"css/page.css\">";
                        });
                    }
                    catch(e) {
                        // fail silently.
                    }
                    FILE_DECL.lastIndex = 0;
                }
                lines[i] = line;
            }
        }

        file.contents = new Buffer(lines.join('\n'));
        cb(null, file);
    });
}